const user_id_hidden = document.getElementById("user_id_hidden")
const receivers_select
    // =document.getElementById("RECEIVER")
    = document.getElementsByClassName("select")[0]

const messages_display=document.getElementById("messages_display")

setTimeout(fetch_messages, 1000)
setTimeout(fetch_users, 1000)

var message_array;
let users_array;

function fetch_users() {
    fetch('hello', {
        method: 'GET', headers: {
            username_readonly: user_id_hidden.value, CHATROOM_SELECT_RECEIVER: true,
        }
    })
        .then(res => res.json())
        .catch(err => console.log(err))
        .then(users => addReceivers(users))
        .catch(err => console.log(err))
    setTimeout(fetch_users, 5000)

}

function addReceivers(users) {
    console.log(users);
    users_array = users;
    let all_users_opt = document.createElement("option");
    all_users_opt.value = "__all__"
    all_users_opt.textContent = "所有人"
    receivers_select.replaceChildren();
    receivers_select.appendChild(all_users_opt);
    for (let i = 0; i < users.length; i++) {
        let username_select = users[i]
        let user_select = document.createElement("option");
        user_select.value = username_select;
        user_select.textContent = username_select;
        receivers_select.appendChild(user_select);
    }
}

function fetch_messages() {
    fetch('chatroom', {
        method: 'GET', headers: {
            username_readonly: user_id_hidden.value, CHATROOM_SELECT_RECEIVER: true,
        }
    })
        .then(res => res.json())
        .catch(err => console.log(err))
        .then(messages => show_messages(messages))
        .catch(err => console.log(err))
    setTimeout(fetch_messages, 5000)
}
function show_messages(messages) {
    console.log("Fetched messages:")
    console.log(messages)
    messages_display.textContent=""
    for(let i = 0; i < messages.length; i++) {
        let message = messages[i]
        let sender=message["sender"]
        let receiver=message["receiver"]
        let content=message["message"]
        let mode
        if("__all__"===receiver){
            mode="公告"
        }
        else{
            mode="私信"
        }
        let display="["+mode+"]"+sender+":"+content+"\n"
        messages_display.textContent+=display
    }
}


